{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "95af877f",
   "metadata": {},
   "source": [
    "## Matrix Multiplication"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e2c169a0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[19., 22.],\n",
      "        [43., 50.]])\n",
      "tensor([[23., 34.],\n",
      "        [31., 46.]])\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "\n",
    "A = torch.tensor([[1, 2], \n",
    "                  [3, 4]])\n",
    "\n",
    "B = torch.tensor([[5, 6], \n",
    "                  [7, 8]])\n",
    "\n",
    "#print(A @ B)\n",
    "#print(B @ A)\n",
    "\n",
    "def matmul(A, B):\n",
    "    ar,ac = A.shape # rows and columns of A\n",
    "    br, bc = B.shape # rows and columns of B\n",
    "\n",
    "    assert ac == br, \"Number of columns in A must match number of rows in B\"\n",
    "\n",
    "    c = torch.zeros(ar, bc)\n",
    "\n",
    "    for i in range(ar):\n",
    "        for j in range(bc):\n",
    "            for k in range(ac): # or br\n",
    "                c[i,j] += A[i,k] * B[k,j]\n",
    "    return c\n",
    "\n",
    "print(matmul(A, B))\n",
    "print(matmul(B, A))\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
